package com.campus.service.impl;

import com.campus.dao.UserDao;
import com.campus.model.User;
import com.campus.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public Optional<User> getUserByLoginName(String loginName) {
        return userDao.findByLoginName(loginName);  // 查询用户
    }

    @Override
    public Optional<Integer> getRoleIdByUserId(Integer userId) {
        return userDao.getRoleIdByUserId(userId);  // 查询用户角色
    }

    @Override
    public boolean validateLogin(String loginName, String password) {
        // 验证用户名和密码
        Optional<User> userOptional = getUserByLoginName(loginName);
        if (userOptional.isPresent()) {
            User user = userOptional.get();
            return password.equals(user.getPassword());  // 比较密码
        }
        return false;
    }

    @Override
    public boolean createUserWithRole(User user, Integer roleId) {
        if (roleId == null || roleId <= 0) {
            throw new IllegalArgumentException("Invalid roleId");
        }
        return userDao.addUser(user, roleId);
    }

    @Override
    public User getUserById(Integer id) {
        return userDao.getUserById(id);  // 根据 ID 查询用户
    }

    @Override
    public boolean updateUser(User user) {
        return userDao.updateUser(user) > 0;
    }

    @Override
    public boolean deleteUser(Integer id) {
        return userDao.deleteUser(id) > 0;
    }

    @Override
    public void updateUserToken(int userId, String token) {
        userDao.updateUserToken(userId, token);  // 调用 DAO 层更新 Token
    }

    @Override
    public Optional<String> getLoginNameByToken(String token) {
        return userDao.getLoginNameByToken(token);  // 调用 DAO 层获取 login_name
    }

    @Override
    public List<User> getAllUsers() {
        return userDao.findAllUsers();
    }

}
